﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SingletonDemo
{
    public class SingleTon2
    {
        private static SingleTon2 singleTon2 = null;

        private SingleTon2()
        {

        }

        private static readonly object obj = new object();

        public static SingleTon2 Instance()
        {
            //懒汉模式，什么时候调用，什么时候初始化
            if (singleTon2 == null)
            {
                lock (obj)//线程锁,Lock是只能在进程内锁，不能跨进程
                {
                    //临界区
                    if (singleTon2 == null)
                    {
                        singleTon2 = new SingleTon2();
                    }
                }

            }
            return singleTon2;
        }


        public int Add()
        {
            return 777;
        }

        public int Update()
        {
            return 666;
        }
    }

    public class SingleTon3
    {
        //单例模式 -饿汉模式
        private static SingleTon3 singleTon3 = new SingleTon3();

        private SingleTon3()
        {

        }

        public static SingleTon3 Instance()
        {
            return singleTon3;
        }


        public int Add()
        {
            return 777;
        }

        public int Update()
        {
            return 666;
        }
    }


    public class SingleTon4
    {
        //单例模式 -饿汉模式
        private static SingleTon4 singleTon4 = new SingleTon4();

        private SingleTon4()
        {

        }

        public static SingleTon4 Instance
        {
            get
            {
                return singleTon4;
            }
        }


        public int Add()
        {
            return 777;
        }

        public int Update()
        {
            return 666;
        }
    }
}
